package com.example.spring.security.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
public class SecurityController {
    private RequestCache requestCode = new HttpSessionRequestCache();


    private RedirectStrategy redirect = new DefaultRedirectStrategy();

    @GetMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws Exception{

        SavedRequest savedRequest = requestCode.getRequest(request, response);
        if(savedRequest != null){
            String target = savedRequest.getRedirectUrl();
            log.info("引发跳转请求："+ target);
            if(StringUtils.endsWithIgnoreCase(target,".html")){
                redirect.sendRedirect(request,response,"/sigin.html");//这是默认登陆页
            }
        }
        return "sigin";//这是自定义登陆页
    }

    @GetMapping("/authentication/mobile")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public String mobileAuthentication(HttpServletRequest request, HttpServletResponse response) throws Exception{
        return "sigin";//这是自定义登陆页
    }

    @GetMapping("/sigin")
    public String sigin(){
        return "sigin";
    }
}
